package org.ank.food;



import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class AdviceProvider extends ContentProvider{

	private static final String AUTHORITY = "org.ank.food.adviceprovider";
	
	private static final String DATABASE_NAME = "advices.db";
	private static final int DATABASE_VERSION = 1;
	private static final String ADVICES_TABLE_NAME = "advices";
	private static final String EATEN_TABLE_NAME = "eaten";
	private static final String EXCEEDINGS_TABLE_NAME = "exceedings";
	private static final String DEFAULT_SORT_ORDER = "profile_id ASC";
	public static final Uri CONTENT_URI_ADVICES = Uri.parse("content://" + AUTHORITY + "/" 
			+ ADVICES_TABLE_NAME);
	public static final Uri CONTENT_URI_EATEN = Uri.parse("content://" + AUTHORITY + "/" 
			+ EATEN_TABLE_NAME);
	public static final Uri CONTENT_URI_EXCEEDINGS = Uri.parse("content://" + AUTHORITY + "/" 
			+ EXCEEDINGS_TABLE_NAME);
	
	public static final String[] COLUMN_NAMES = {"_id","profile_id","product_id","product_name",
		"weight_item_id","weight_item_name","weight_item_amount","weight_of_item"};
	public static final String[] COLUMN_TYPES = {"integer primary key","integer","integer","text"
		,"integer","text","integer","float"};
	public static final int ID = 0;
	public static final int PROFILE_ID = 1;
	public static final int PRODUCT_ID = 2;
	public static final int PRODUCT_NAME = 3;
	public static final int WEIGHT_ITEM_ID = 4;
	public static final int WEIGHT_ITEM_NAME = 5;
	public static final int WEIGHT_ITEM_AMOUNT = 6;
	public static final int WEIGHT_ITEM_WEIGHT = 7;
	
	
	public static final String[] COLUMN_NAMES_EXCEEDINGS = {"_id","profile_id","prot_exceeding",
		"fat_exceeding","carbo_exceeding"};
	public static final String[] COLUMN_TYPES_EXCEEDINGS = {"integer primary key",
		"integer","integer","integer","integer"};
	public static final int PROT_EXCEEDING = 2;
	public static final int FAT_EXCEEDING = 3;
	public static final int CARBO_EXCEEDING = 4;
	
	
	public static final int ADVICES = 2;
	public static final int EATEN = 3;
	public static final int EXCEEDINGS = 4;
	
	
	 
	private UriMatcher sUriMatcher; 
	 
	private static class DatabaseHelper extends SQLiteOpenHelper {
		 
		public DatabaseHelper(Context context) {
			 super(context, DATABASE_NAME, null, DATABASE_VERSION);
		 }

		 @Override
		 public void onCreate(SQLiteDatabase db) {
//			 StringBuffer bufAdvices = new StringBuffer("CREATE TABLE ");
			 StringBuffer bufEaten = new StringBuffer("CREATE TABLE ");
//			 StringBuffer bufExceedings = new StringBuffer("CREATE TABLE ");
//			 bufAdvices.append(ADVICES_TABLE_NAME).append("(");
			 bufEaten.append(EATEN_TABLE_NAME).append("(");
//			 bufExceedings.append(EXCEEDINGS_TABLE_NAME).append("(");
			 for( int i = 0; i < COLUMN_NAMES.length-1; i++ ){
//				 bufAdvices.append(COLUMN_NAMES[i]).append(' ').append(COLUMN_TYPES[i]).append(", ");
				 bufEaten.append(COLUMN_NAMES[i]).append(' ').append(COLUMN_TYPES[i]).append(", ");
			 }
//			 for( int i = 0; i < COLUMN_NAMES_EXCEEDINGS.length-1; i++ ){
//				 bufExceedings.append(COLUMN_NAMES_EXCEEDINGS[i]).append(' ').
//				 		append(COLUMN_TYPES_EXCEEDINGS[i]).append(", ");
//			 }
//			 bufAdvices.append(COLUMN_NAMES[COLUMN_NAMES.length-1]).append(' ').
//			 	append(COLUMN_TYPES[COLUMN_TYPES.length-1]).append(");");
			 bufEaten.append(COLUMN_NAMES[COLUMN_NAMES.length-1]).append(' ').
			 	append(COLUMN_TYPES[COLUMN_TYPES.length-1]).append(");");
//			 bufExceedings.append(COLUMN_NAMES_EXCEEDINGS[COLUMN_NAMES_EXCEEDINGS.length-1]).append(' ').
//			 	append(COLUMN_TYPES_EXCEEDINGS[COLUMN_TYPES_EXCEEDINGS.length-1]).append(");");
//			 db.execSQL( bufAdvices.toString() );
			 db.execSQL( bufEaten.toString() );
//			 db.execSQL( bufExceedings.toString() );
		 }

		 @Override
		 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//			 db.execSQL("DROP TABLE IF EXISTS "+ADVICES_TABLE_NAME+";");
			 db.execSQL("DROP TABLE IF EXISTS "+EATEN_TABLE_NAME+";");
//			 db.execSQL("DROP TABLE IF EXISTS "+EXCEEDINGS_TABLE_NAME+";");
	         onCreate(db);
		 }
	 }
	
	 private DatabaseHelper mOpenHelper;
	
	 @Override
	 public int delete(Uri uri, String where, String[] whereArgs) {
		 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		 int a = 0;
		 
		 switch(sUriMatcher.match(uri)){
		 case ADVICES :
			 a = db.delete(ADVICES_TABLE_NAME, where, whereArgs);
			 getContext().getContentResolver().notifyChange(uri, null);
			 break;
		 case EATEN :
			 a = db.delete(EATEN_TABLE_NAME, where, whereArgs);
			 getContext().getContentResolver().notifyChange(uri, null);
			 break;
		 case EXCEEDINGS :
			 a = db.delete(EXCEEDINGS_TABLE_NAME, where, whereArgs);
			 getContext().getContentResolver().notifyChange(uri, null);
			 break;
		 default :
			 throw new IllegalArgumentException("Unknown URI " + uri);
		 }
	     return a;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId;
        switch (sUriMatcher.match(uri)){
        case ADVICES :
        	rowId = db.insert(ADVICES_TABLE_NAME, COLUMN_NAMES[1], values);
        	if (rowId >= 0) {
        		Uri noteUri = ContentUris.withAppendedId(CONTENT_URI_ADVICES, rowId);
        		getContext().getContentResolver().notifyChange(noteUri, null);
        		return noteUri;
        	}
        	break;
        case EATEN :
        	rowId = db.insert(EATEN_TABLE_NAME, COLUMN_NAMES[1], values);
            if (rowId >= 0) {
                Uri noteUri = ContentUris.withAppendedId(CONTENT_URI_EATEN, rowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                return noteUri;
            }
            break;
        case EXCEEDINGS :
        	rowId = db.insert(EXCEEDINGS_TABLE_NAME, COLUMN_NAMES_EXCEEDINGS[1], values);
        	Log.v("advice provider", "insert: values = "+values);
        	Log.v("advice provider", "insert: EXCEEDINGS, rowId = "+rowId);
            if (rowId >= 0) {
                Uri noteUri = ContentUris.withAppendedId(CONTENT_URI_EXCEEDINGS, rowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                return noteUri;
            }
            break;
        default :
        	throw new IllegalArgumentException("Unknown URI " + uri);
        }
        
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, ADVICES_TABLE_NAME, ADVICES);
        sUriMatcher.addURI(AUTHORITY, EATEN_TABLE_NAME, EATEN);
        sUriMatcher.addURI(AUTHORITY, EXCEEDINGS_TABLE_NAME, EXCEEDINGS);
        return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch(sUriMatcher.match(uri)){
		case ADVICES :
			qb.setTables(ADVICES_TABLE_NAME);
			break;
		case EATEN :
			qb.setTables(EATEN_TABLE_NAME);
			break;
		case EXCEEDINGS :
			qb.setTables(EXCEEDINGS_TABLE_NAME);
			break;
		default :
			throw new IllegalArgumentException("Unknown URI " + uri);	
		}
		
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int a;
		switch(sUriMatcher.match(uri)){
		case ADVICES :
			a = db.update(ADVICES_TABLE_NAME, values, where, whereArgs);
			break;
		case EATEN :
			a = db.update(EATEN_TABLE_NAME, values, where, whereArgs);
			break;
		case EXCEEDINGS :
			a = db.update(EXCEEDINGS_TABLE_NAME, values, where, whereArgs);
			break;
		default :
			throw new IllegalArgumentException("Unknown URI " + uri);	
		}
        getContext().getContentResolver().notifyChange(uri, null);
        return a;
	}
}
